#include <devices_ext/ch452.h>
static inline void clk_tick( void )
{
	/* AVR指令执行时间是1000000000/14745600 = 67ns，根据说明书，两条nop执行时间足够ch452分辨了 */
	cbio( CH452_PORT, CH452_CLK );
	nop();
	nop();
	sbio( CH452_PORT, CH452_CLK );
	nop();
	nop();
}

static inline void load_data( void )
{
	sbio( CH452_PORT, CH452_LOAD );
	nop();
	nop();
	cbio( CH452_PORT, CH452_LOAD );
}

void ch452_write( uint16_t data )
{
	uint8_t i ;
	for( i = 0; i < 12; ++i ){
		if( data & ( 1 << i ) ){
			sbio( CH452_PORT, CH452_DIN );
		} else {
			cbio( CH452_PORT, CH452_DIN );
		}
		clk_tick();
	}
	load_data();
}

uint16_t ch452_read( uint8_t bits )
{
	uint16_t data = 0;
	uint8_t i;
	for( i = 0; i < bits; ++i ){
		clk_tick();
		if( bit_is_set( CH452_PIN, CH452_DOUT ) )
			data |= _BV(i);
	}
	return data;
}
